set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

create   procedure [dbo].[a_Article_RSS]
@TypeCat tinyint,
@CatID varchar(50) = '', 
@NumTop varchar(50)
AS
set nocount on
declare @str varchar(1000)

if @TypeCat  =0 		-- all site
begin
	create table #temp
	(
		TID int identity(1,1),
		AID int
	)
	
	-- get featured article
	insert into #temp (AID) 
	select [ID]
	from a_Articles 
	where PublishStatus = 1 and isFeatured =1 and FeaturedType > 0
	order by FeaturedType
	
	
	-- get normal article
	declare @t1 int , @t2 int
	select @t1 = count(*) from #temp
	
	set @t2 = convert(int, @Numtop) - isnull(@t1, 0) 
	
	set @str = ' insert into #temp (AID)
			select top ' + convert(varchar(50), @t2) + ' [ID]
			from a_Articles A
			where PublishStatus = 1 and isFeatured = 0 and FeaturedType = 0
			order by PublishDate desc, PostDate desc'
--	print @str
		Exec(@str)
	
	
	--OUT PUT RESULT 
	select [ID], uTitle, kTitle,
			isnull((select ImageNo from a_Articles_Img AI where AI.AID = A.ID and isMainImg = 1 ),0) as ImageNo,
			SUBSTRING( ubody, 1 , CHARINDEX('.', convert(nvarchar(500), ubody) + '.') )  + '...'as uBody, a.fYear
	from #temp T INNER JOIN a_Articles a ON T.AID = A.[ID]
	order by TID

	DROP table #temp
end
else
if @TypeCat = 1 		--- specify category
begin
	set @str = '
		select top ' + @NumTop + ' [ID], uTitle, kTitle,
		isnull((select ImageNo from a_Articles_Img AI where AI.AID = A.ID and isMainImg = 1 ),0) as ImageNo,
		SUBSTRING( ubody, 1 , CHARINDEX(''.'', convert(nvarchar(500), ubody) + ''.'') ) + ''...'' as uBody, a.fYear
		from a_Articles	A 
		where PublishStatus = 1 and MainCatID = ' + @CatID + '
		order by PublishDate desc, PostDate desc'
	Exec(@str)
end



